package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.BbsActionLog;
import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.MqMessageLog;
import cn.pconline.autoclub.mq.MessageListener;
import cn.pconline.autoclub.service.BbsActionLogService;
import cn.pconline.autoclub.service.DynaBbsActionLogService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.WebUtils;
import com.alibaba.fastjson.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 论坛同步日志（动态、回复）
 *
 * @author zhouruxuan
 * @date 2014年9月2日 上午10:20:54
 */
@Controller
public class DynaBbsSyncController {
    private static final Logger log = LoggerFactory.getLogger(DynaBbsSyncController.class);
    @Autowired
    private DynaBbsActionLogService dynaBbsActionLogService;
    @Autowired
    private BbsActionLogService bbsActionLogService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageListener messageListener;
    @Autowired
    private EffectiveDynaService dynaService;
    @Autowired
    private GeliDao geliDao;

    @RequestMapping(value = "/bbs/dynaReceive.do")
    @ResponseBody
    public String receive(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("gbk");
        long logId = NumberUtils.toLong(request.getParameter("logId"));
        long topicId = NumberUtils.toLong(request.getParameter("topicId"));
        long forumId = NumberUtils.toLong(request.getParameter("forumId"));
        long userId = NumberUtils.toLong(request.getParameter("userId"));
        long createAt = NumberUtils.toLong(request.getParameter("createAt"));
        int typeId = NumberUtils.toInt(request.getParameter("typeId"));
        String content = request.getParameter("content");
       
        BbsActionLog actionLog = new BbsActionLog();
        actionLog.setLogId(logId);
        actionLog.setTopicId(topicId);
        actionLog.setForumId(forumId);
        actionLog.setUserId(userId);
        actionLog.setContent(content);
        actionLog.setTypeId(typeId);
        actionLog.setCreateAt(new Date(createAt));

        try {
            dynaBbsActionLogService.service(actionLog, typeId);//新版同步
            bbsActionLogService.service(actionLog, typeId);//旧版同步
        } catch (Exception e) {
            log.error("sync topic info error: {}", content);
            log.error("sync topic info error", e);
        }
        return "";
    }
    
    @RequestMapping(value = "/dyna/syncFromLog.do")
    @ResponseBody
    public String syncDynaFromActionLog(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("gbk");
        int num = WebUtils.paramInt(request, "num", 100);
        String createAt = request.getParameter("date");
        Date date = new Date();
        if(StringUtils.isNotBlank(createAt)) {
            Date paramDate = DateUtils.parseDate(createAt, "yyyyMMdd");
            if(paramDate != null) {
                date = paramDate;
            }
        }
        List<BbsActionLog> actionLogs = dynaBbsActionLogService.getTopicCreatActionLog(date, num);
        Map<Long, Integer> statMap = new HashMap<Long, Integer>();
        statMap.put(0L, actionLogs.size());
        for(BbsActionLog actionLog : actionLogs) {
            try {
                dynaBbsActionLogService.reSyncFromActionLog(actionLog);
                log.info("re sync: {}-{}", actionLog.getTopicId(), actionLog.getTypeId());
                List<BbsActionLog> topicActionLogs = dynaBbsActionLogService.getBbsActionLogByTopicId(actionLog.getTopicId(), date);
                statMap.put(actionLog.getTopicId(), topicActionLogs.size());
                for(BbsActionLog topicActionLog : topicActionLogs) {
                    if(topicActionLog.getTypeId() == 100){
                        continue;
                    }
                    log.info("re sync: {}-{}", topicActionLog.getTopicId(), topicActionLog.getTypeId());
                    dynaBbsActionLogService.reSyncFromActionLog(topicActionLog);
                }
            } catch (Exception e) {
                log.error("sync topic info error", e);
            }
        }
        return statMap.toString();
    }
    
    @RequestMapping(value = "/dyna/syncFromMqmsg.do")
    @ResponseBody
    public String syncFromMqmsg(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("gbk");
        long msgId = WebUtils.paramLong(request, "msgId", 0L);
        if(msgId == 0) {
            return "msgId is 0";
        }
        Date date = new Date();
        try {
            date = WebUtils.parseDate("date");
        } catch (Exception e) {
            log.error("date param not right: {}", request.getParameter("date"));
        }
        MqMessageLog messageLog = geliDao.find(MqMessageLog.class, date.getTime(), msgId);
        messageListener.onMessage(JSONObject.parseObject(messageLog.getMessage()));
        return messageLog.getMessage();
    }
    
    @RequestMapping(value = "/dyna/repairClubDyna.do", method=RequestMethod.POST)
    @ResponseBody
    public String repairClubDyna(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("gbk");
        int type = WebUtils.paramInt(request, "type", 1);
        Calendar cal = Calendar.getInstance();
        try {
            Date date = WebUtils.parseDate("date");
            cal.setTime(date);
        } catch (Exception e) {
            log.error("date param not right: {}", request.getParameter("date"));
        }
        long infoId = WebUtils.paramLong(request, "infoId", 0L);
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select a.dyna_info_id,a.club_id dyna_club_id,b.club_id member_club_id");
        sqlBuilder.appendSql(" from ac_dyna_info_" + cal.get(Calendar.YEAR) + " a,ac_member_info b ");
        sqlBuilder.appendSql(" where a.create_by = b.user_id ");
        sqlBuilder.appendSql(" and a.type = ").appendValue(type);
        if(infoId > 0) {
            sqlBuilder.appendSql(" and a.dyna_info_id = ").appendValue(infoId);
        } else {
            sqlBuilder.appendSql(" and a.club_id <> b.club_id");
        }
        log.info("sql: {}, param: {}",sqlBuilder.getSql(), Arrays.toString(sqlBuilder.getValues()));
        List<Map<String, Object>> result = geliDao.getJdbcTemplate().queryForList(sqlBuilder.getSql(), sqlBuilder.getValues());
        if(result != null) {
            for(Map<String, Object> row : result) {
                    long dynaInfoId = NumberUtils.toLong(""+row.get("dyna_info_id"));
                    long dynaClubId = NumberUtils.toLong(""+row.get("dyna_club_id"));
                    long memberClubId = NumberUtils.toLong(""+row.get("member_club_id"));
                try {
                    if(dynaInfoId > 0) {
                        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, cal.getTime());
                        if (dynaInfo != null) {
                            dynaInfo.setClubId(memberClubId);
                            dynaService.updateDyna(dynaInfo, "club_id");
                        }
                        
                        ClubDyna clubDyna1 = dynaService.findClubDynaById(dynaInfoId, dynaClubId);
                        ClubDyna clubDyna2 = dynaService.findClubDynaById(dynaInfoId, memberClubId);
                        if (clubDyna1 != null) {
                            if (clubDyna2 == null) {
                                clubDyna1.setClubId(memberClubId);
                                clubDyna1.setPick(dynaInfo.getPick());
                                clubDyna1.setRecommend(dynaInfo.getRecommend());
                                clubDyna1.setStatus(DynaInfo.STATUS_NORMAL);
                                geliDao.update(clubDyna1, "club_id,pick,recommend,status");
                                log.warn("dyna1[{}] clubId[{}] change to [{}] success", dynaInfoId, dynaClubId, memberClubId);
                            } else {
                                clubDyna2.setClubId(memberClubId);
                                clubDyna2.setPick(dynaInfo.getPick());
                                clubDyna2.setRecommend(dynaInfo.getRecommend());
                                clubDyna2.setStatus(DynaInfo.STATUS_NORMAL);
                                geliDao.update(clubDyna2, "club_id,pick,recommend,status");
                                geliDao.delete(clubDyna1, new Mid(dynaClubId, dynaInfoId));
                                log.warn("dyna2[{}] clubId[{}] update to [{}] success", dynaInfoId, dynaClubId, memberClubId);
                            }
                        } else {
                            if (clubDyna2 != null) {
                                clubDyna2.setClubId(memberClubId);
                                clubDyna2.setPick(dynaInfo.getPick());
                                clubDyna2.setRecommend(dynaInfo.getRecommend());
                                clubDyna2.setStatus(DynaInfo.STATUS_NORMAL);
                                geliDao.update(clubDyna2, "club_id,pick,recommend,status");
                                
                                dynaInfo.setClubId(memberClubId);
                                dynaService.updateDyna(dynaInfo, "club_id");
                                log.warn("dyna2[{}] clubId[{}] update to [{}] success", dynaInfoId, dynaClubId, memberClubId);
                            } else {
                                
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("dyna[{}] clubId[{}] change to [{}] error", dynaInfoId, dynaClubId, memberClubId);
                }
            }
            return ""+result.size();
        }
        return "0";
    }
    
    @RequestMapping(value = "/dyna/deleteClubDyna.do", method=RequestMethod.POST)
    @ResponseBody
    public String deleteClubDyna(HttpServletRequest request) throws Exception {
        long infoId = WebUtils.paramLong(request, "infoId", 0L);
        Calendar cal = Calendar.getInstance();
        try {
            Date date = WebUtils.parseDate("date");
            cal.setTime(date);
        } catch (Exception e) {
            log.error("date param not right: {}", request.getParameter("date"));
        }
        DynaInfo dynaInfo = dynaService.findDynaById(infoId, cal.getTime());
        if(dynaInfo != null) {
            long count = dynaService.deleteClubDyna(dynaInfo.getClubId(), dynaInfo.getDynaInfoId());
            dynaInfo.setClubId(0);
            dynaService.updateDyna(dynaInfo, "club_id");
            return ""+count;
        }
        return "0";
    }
    
    @RequestMapping(value = "/dyna/changeDynaToClub.do", method=RequestMethod.POST)
    @ResponseBody
    public String changeDynaToClub(HttpServletRequest request) throws Exception {
        long infoId = WebUtils.paramLong(request, "infoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        ClubDyna clubDyna1 = dynaService.findClubDynaById(infoId, clubId);
        if(clubDyna1 != null) {
            int count = 0;
            DynaInfo dynaInfo = dynaService.findDynaById(clubDyna1.getDynaInfoId(), clubDyna1.getCreateDate());
            ClubDyna clubDyna2 = dynaService.findClubDynaById(clubDyna1.getDynaInfoId(), dynaInfo.getClubId());
            count += geliDao.delete(clubDyna1, new Mid(clubDyna1.getClubId(), clubDyna1.getDynaInfoId()));
            if(clubDyna2 == null) {
                clubDyna1.setClubId(dynaInfo.getClubId());
                clubDyna1.setPick(dynaInfo.getPick());
                clubDyna1.setRecommend(dynaInfo.getRecommend());
                clubDyna1.setPostCount(dynaInfo.getPostCount());
                clubDyna1.setLastPostAt(dynaInfo.getLastPostAt());
                geliDao.create(clubDyna1);
                count += 1;
            }
            return ""+count;
        }
        return "0";
    }
}
